{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "14244f22",
   "metadata": {},
   "source": [
    "## 环形列表\n",
    "[环形列表](https://leetcode.cn/problems/linked-list-cycle-ii/)\n",
    "快慢指针法：定义fast和slow指针，让fast领先slow两个节点，这样如果存在环形结构，那么两者就会相遇。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ba2dd7c2",
   "metadata": {},
   "outputs": [],
   "source": [
    "class ListNode:\n",
    "    def __init__(self,val:int =0,next=None):\n",
    "        self.val = val\n",
    "        self.next = next\n",
    "\n",
    "class Solution:\n",
    "    def detectCycle(self,head:ListNode) -> ListNode:\n",
    "        slow = head\n",
    "        fast = head\n",
    "\n",
    "        while fast and fast.next:\n",
    "            slow = slow.next\n",
    "            fast = fast.next.next\n",
    "\n",
    "            if slow == fast:\n",
    "\n",
    "                slow = head\n",
    "                while slow != fast:\n",
    "                    slow = slow.next\n",
    "                    fast = fast.next\n",
    "\n",
    "                return slow\n",
    "        return None\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "env_py38",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python",
   "version": "3.8.18"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
